How do I sort a generic list?
How do I sort a generic list?
480
18-Aug-2023
Aryan Kumar
19-Aug-2023To sort a generic list in C#, you can use the
Sort()method. TheSort()method takes a delegate as its parameter. The delegate is a function that takes two objects of the same type and returns an integer.The following code sorts a generic list of strings in ascending order:
C#
In this example, the delegate takes two strings as its parameters and returns an integer. The integer returned by the delegate indicates the order of the two strings. In this case, the delegate compares the two strings lexicographically and returns a negative integer if the first string is less than the second string, a positive integer if the first string is greater than the second string, and 0 if the two strings are equal.
The
Sort()method will sort the list in ascending order by default. If you want to sort the list in descending order, you can passtrueas the second parameter to theSort()method.Here is the code to sort the list in descending order:
C#
The
Sort()method can also be used to sort lists of objects that implement theIComparableinterface. TheIComparableinterface defines a single method,CompareTo(), which takes another object of the same type as its parameter and returns an integer. The integer returned by theCompareTo()method indicates the order of the two objects.The following code sorts a list of objects that implement the
IComparableinterface:C#
In this example, the
Personclass implements theIComparableinterface. TheCompareTo()method compares the ages of the twoPersonobjects and returns the difference.